﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using JCore.LoLChat;
using LoL_Profiler;

namespace JCore.LoLProfiler_Test.Classes.API
{
    public class JSONdownloader
    {
        public static ElophantAPI.Summoner.Data SummonerProfile (string summonerName)
        {
            using (WebClient client = new WebClient())
            {
                int sleep = 1000;
                Retry:
                string jsonProfileSummonerInfo =
                    client.DownloadString(String.Format(@"http://api.elophant.com/v2/{0}/summoner/{1}?key={2}",
                                                        "euw", summonerName, frmGetInfoTest.key));
                ElophantAPI.Summoner.RootObject response =
                    ElophantAPI.Summoner.getProfileSummonerInfo(jsonProfileSummonerInfo);
                if (response.success)
                {
                    return response.data;
                }
                else
                {
                    Console.WriteLine(response.error);
                    if (sleep <= 10000)
                    {
                        sleep += 1000;
                        Thread.Sleep(sleep);
                        goto Retry;
                    }
                    MessageBox.Show("De API lijkt plat te liggen, probeer het later nog is...\n" + response.error);
                    return null;
                }
            }
        }

        public static ElophantAPI.RecentGames.Data RecentGames(string accountID)
        {
            using (WebClient client = new WebClient())
            {
                int sleep = 1000;
            Retry:
                // JSON query
                string jsonMatches =
                    client.DownloadString(String.Format(@"http://api.elophant.com/v2/{0}/recent_games/{1}?key={2}",
                                                        "euw", accountID, frmGetInfoTest.key));
                // Response to object
                ElophantAPI.RecentGames.RootObject response = ElophantAPI.RecentGames.getRecentGames(jsonMatches);

                // Succes?
                if (response.success)
                {
                    return response.data;
                }
                else
                {
                    Console.WriteLine(response.error);
                    if (sleep <= 10000)
                    {
                        sleep += 1000;
                        Thread.Sleep(sleep);
                        goto Retry;
                    }
                    MessageBox.Show("De API lijkt plat te liggen, probeer het later nog is...");
                    return null;
                }
            }
        }

    }
}
